/**
 * Created by Administrator on 2015/2/1.
 */


var Config = require('./config').Config();
var logger = require('./logger');
var utils = require('./utils');

var AccessToken = null;
exports.getTokenURL = function () {
    var url = Config.tokenBaseURL;
    url += "?grant_type=client_credential";
    url += "&appid=" + Config.appId;
    url += "&secret=" + Config.appSecret;
    return url;
};
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
exports.getUserInfoURL = function (userOpenID) {
    var url = Config.userInfoBaseURL;
    url += "?access_token="+AccessToken['access_token'];
    url += "&openid=" + userOpenID;
    url += "&lang=zh_CN";
    return url;
};

exports.refreshToken = function () {
    if (!AccessToken || checkTokenExpire()) {
        var now = new Date().getTime();
        var result = utils.syncHttpGet(this.getTokenURL());
        result = JSON.parse(result);
        result['obtain'] = now;
        AccessToken = result;
    }
}


var checkTokenExpire = function () {
    var now = new Date().getTime();
    var tokenUse = (now - AccessToken['obtain']) / 1000 + 100; //token过期时间以秒为单位，提前100秒过期
    if (tokenUse > AccessToken['expires_in']) {
        return true;
    } else {
        return false;
    }
}

exports.getUserName = function (userOpenId) {
    this.refreshToken();
    var result = utils.syncHttpGet(this.getUserInfoURL(userOpenId));
    result = JSON.parse(result);
    logger.debug("user info", result)
    var userName = result['nickname'];
    return userName;
}